﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AxMSTSCLib;
using FD.RemoteAssistant.Core;
using FDRemoteAssistant2.Manager;
using MSTSCLib;

namespace FDRemoteAssistant2
{
    /*
     * CreatedOn: 2018-05-15
     * CreatedBy: Jackie Lee(天宇遊龍)
     */
    public partial class RemoteClientPage : TabPage
    {
        private IRemoteSetting _remoteSetting;

        public EventHandler Connected;
        public EventHandler<IRemoteSetting> Disconnected;
        private Rectangle _clientRect;

        #region 初始化
        public RemoteClientPage(IRemoteSetting remoteSetting)
        {
            _remoteSetting = remoteSetting;
            InitializeComponent();
            Init();
        }

        private void Init()
        {
            Text = FDHelper.Current.GetDisplayText(_remoteSetting);
            ToolTipText = FDHelper.Current.GetRemoteName(_remoteSetting, true);
            _client = new AxMsRdpClient9();
            _client.OnConnected += Client_OnConnected;
            _client.OnDisconnected += Client_OnDisconnected;
            //client.OnAuthenticationWarningDismissed += Client_OnAuthenticationWarningDismissed;
            _client.OnWarning += Client_OnWarning;
            _client.OnLogonError += Client_OnLogonError;
            _client.OnFatalError += Client_OnFatalError;
            _client.OnFocusReleased += Client_OnFocusReleased; _client.GotFocus += Client_GotFocus;
            _client.PreviewKeyDown += Client_PreviewKeyDown;
            _client.Dock = DockStyle.Fill;
            Controls.Add(_client);
            _client.OnRemoteDesktopSizeChange += Client_OnRemoteDesktopSizeChange;
            _client.OnEnterFullScreenMode += Client_OnEnterFullScreenMode;
        }
        #endregion

        #region 事件处理
        #region 窗体事件

        #endregion

        #region Client 事件
        private void Client_OnEnterFullScreenMode(object sender, EventArgs e)
        {
            //var scrnRect = Screen.PrimaryScreen.WorkingArea;
            //client.Width = scrnRect.Width;
            //client.Height = scrnRect.Height;
            //client.DesktopHeight = scrnRect.Height;
            //client.DesktopWidth = scrnRect.Width;
            //client.Refresh();

            //client.ClientSize = scrnRect.Size;
        }

        private void Client_OnRemoteDesktopSizeChange(object sender, IMsTscAxEvents_OnRemoteDesktopSizeChangeEvent e)
        {
            if (_clientRect.IsEmpty)
            {
                _clientRect.Height = e.height;
                _clientRect.Width = e.width;
            }
        }

        private void Client_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {
            if (e.KeyCode == Keys.Menu)
            {

            }
        }

        private bool _bRemotingMode;
        private void Client_GotFocus(object sender, EventArgs e)
        {
            _bRemotingMode = true;
        }

        private void Client_OnFocusReleased(object sender, IMsTscAxEvents_OnFocusReleasedEvent e)
        {
            _bRemotingMode = false;
        }

        private void Client_OnWarning(object sender, IMsTscAxEvents_OnWarningEvent e)
        {
            MessageBox.Show("Client_OnWarning:" + e.warningCode);
        }

        private void Client_OnFatalError(object sender, IMsTscAxEvents_OnFatalErrorEvent e)
        {
            MessageBox.Show("Client_OnFatalError:" + e.errorCode);
        }

        private void Client_OnLogonError(object sender, IMsTscAxEvents_OnLogonErrorEvent e)
        {
            MessageBox.Show("Client_OnLogonError:" + e.lError);
        }

        private void Client_OnAuthenticationWarningDismissed(object sender, EventArgs e)
        {
            MessageBox.Show("Client_OnAuthenticationWarningDismissed");
        }

        private AxMsRdpClient9 _client;

        private void Client_OnDisconnected(object sender, IMsTscAxEvents_OnDisconnectedEvent e)
        {
            //if (e.discReason == 1)
            //{
            //    client.Disconnect();
            //}

            Disconnected?.Invoke(sender, _remoteSetting);
            //MessageBox.Show("断开");
        }

        private void Client_OnConnected(object sender, EventArgs e)
        {
            Connected?.Invoke(sender, e);
        }
        #endregion
        #endregion

        #region 逻辑处理

        /// <summary>
        /// 是否全屏
        /// </summary>
        public bool IsFullScreen
        {
            get => _client.FullScreen;
            set => _client.FullScreen = value;
        }

        public void Connect()
        {
            var server = _remoteSetting.Server;
            int port = 0;
            if (server.IndexOf(',') != -1)
            {
                var items = server.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                server = items[0];
                int.TryParse(items[1], out port);
            }
            _client.Server = server;// "192.168.1.174";
            if (port > 0)
                _client.AdvancedSettings5.RDPPort = port;
            _client.Domain = _remoteSetting.Domain;//"192.168.1.174";
            _client.UserName = _remoteSetting.UserName;// "administrator";
            _client.AdvancedSettings5.ClearTextPassword = _remoteSetting.Password;// "XSb123456";
            _client.AdvancedSettings5.RedirectDrives = _remoteSetting.RedirectDrives;// true;
            _client.AdvancedSettings5.RedirectPrinters = _remoteSetting.RedirectPrinters;//true;
            _client.AdvancedSettings5.RedirectPorts = _remoteSetting.RedirectPorts;//true;
            _client.AdvancedSettings5.RedirectSmartCards = _remoteSetting.RedirectSmartCards;//true;
            var scrnRect = Screen.GetWorkingArea(this);
            if (_remoteSetting.IsFullscreen)
            {
                _client.DesktopHeight = scrnRect.Height;
                _client.DesktopWidth = scrnRect.Width;
                IsFullScreen = true;
            }

            _client.Connect();
        }

        public void Disconnect()
        {
            try
            {
                _client.Disconnect();
                _client.Dispose();
                _client = null;
            }
            catch { }
        }
        #endregion
    }
}
